text_page.admin = liwe.module ( "text_page.admin" );

text_page.admin.list = function ( dest_div )
{
	text_page.admin.ajax ( { "action": "text_page.admin.list" }, function ( v )
		{
			$ ( dest_div ).innerHTML = text_page.admin._format_list ( v [ 'text_pages' ] );
		} );
};

text_page.admin._format_list = function ( rows )
{
	var t, l = rows.length;
	var s = '';
	var templ = text_page.admin.templates [ 'table_row' ];
	var r;
	
	for ( t = 0; t < l; t ++ )
	{
		r = rows [ t ];
		r [ '_actions' ] = '';
		//TODO: verificare se possiede i permessi necessari lato client

		r [ '_actions' ]  = String.formatDict ( text_page.admin.templates [ 'del_item' ], r );
		r [ '_actions' ] += ' - ' + String.formatDict ( text_page.admin.templates [ 'edit_item' ], r );


		s += String.formatDict ( templ, r );
	}

	if ( l > 0 ) s = text_page.admin.templates [ 'table_start' ] + s + text_page.admin.templates [ 'table_end' ];

	return s;
};

text_page.admin.add = function ()
{
	text_page.admin._create_set_frm ( "block_main" );
};

text_page.admin._create_set_frm = function ( dest_div, text_data )
{
	if ( ! text_data ) text_data = {};

	var f = new liwe.form.instance ( "text_page_frm" );

	var taglist = tags.convert ( text_data.get ( "tags" ) );

	/* var vis = text_data.get ( "visible", -1 );

	if ( vis == -1 || vis == 1) vis = true;
	else vis = false;
	*/

	f.hidden ( 'id_page', text_data.get ( 'id_page', 0 ) );
	f.hidden ( 'id_page_man', text_data.get ( 'id_page_man', 0 ) );
	f.hidden ( "action", "text_page.admin.create" );
	f.text ( { label: "Titolo", maxlength: 64, size: 40, name: "title", mandatory: true, value: text_data.get ( "title", "" ) } );
	f.rte  ( { label: "Testo",  name: "text", value: text_data.get ( "txt", "" ) } );
	// f.checkbox ( { name: 'visible', label: 'Visibile', checked: vis, value: 1 } );
	f.tags ( { label: 'Tags', name: 'tags', value: tags.convert ( text_data.get ( "tags" ) ) } );
	f.button ( { name:'btn_save', onclick: 'text_page.admin._save()', value: 'SALVA' } );

	f.set ( dest_div );
};

text_page.admin._save = function ()
{
	var f = liwe.form.get ( "text_page_frm" );
	var dct = f.get_values ();

	text_page.admin.ajax ( dct, function ( v ) 
		{
                	liwe.utils.notifier.fx = true;
                	liwe.utils.notifier.show ( "Pagina salvata correttamente" );
                	setTimeout ( liwe.utils.notifier.hide, 2000 );
		} );
};

text_page.admin.edit = function ( dest_div, id_page )
{
	text_page.get ( id_page, function ( v ) {
		text_page.admin._create_set_frm ( dest_div, v.get ( 'text_page' ) );
	} );
};

text_page.admin.del = function ( dest_div, id_page )
{
	if ( ! id_page ) return;

	if ( confirm ( "Sei sicuro di voler eliminare?" ) )
	{
		liwe.AJAX.easy ( { 'id_page': id_page, 'action': "text_page.admin.delete" }, function ( v ) {
			text_page.admin.list ( dest_div );
		} );
	}
};
